package cn.b.sky.mes.hr.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import cn.b.sky.mes.hr.model.Performance;
import cn.b.sky.mes.hr.model.Personnel;
import cn.b.sky.mes.hr.model.ShiftingPermission;
import cn.b.sky.mes.hr.model.condition.PerformanceCondition;
import cn.b.sky.mes.hr.service.PersonnelPerformanceService;
import cn.b.sky.mes.hr.service.PersonnelService;
import cn.b.sky.mes.hr.service.ShiftingPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.common.utils.DateUtils;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;

@Controller
@RequestMapping(value = "/hr_personnelPerformance/*")
@Slf4j
public class PersonnelPerformanceAnalysisController extends SecurityController {
  @Autowired
  private PersonnelService personnelService;

  @Autowired
  private PersonnelPerformanceService personnelPerformanceService;

  @Resource
  private ShiftingPermissionService shiftingPermissionService;

  @RequestMapping("index")
  public String index(String navTabId, @ModelAttribute("condition") PerformanceCondition condition, Model model)
      throws ParseException {

    model.addAttribute(NAVTABID, navTabId);
    //初始化日期区间。起止日期默认间隔一周
    if (StringUtils.isBlank(condition.getMinTheDate())) {
      condition.setMinTheDate(DateUtils.getDateUtils(DateUtils.YYYY_MM_DD).format(new Date()));
      if (StringUtils.isBlank(condition.getMaxTheDate())) {
        condition
            .setMaxTheDate(DateUtils.getDateUtils(DateUtils.YYYY_MM_DD).operationDay(condition.getMinTheDate(), 6));
      }
    }
    //获取当前用户的工作中心权限
    List<ShiftingPermission> workCenters = shiftingPermissionService.getPermissionsByUser(this.getSiteCode(),
        SecurityContextUtil.getCurrentUserName(), null);
    //没有工作中心权限则不过滤
    if (workCenters == null || workCenters.size() <= 0) {
      model.addAttribute("page", condition);
      return "hr/performance/personnelPerf_statistics";
    }
    condition.setPermission(workCenters);
    //同时可以比较的人员数量限制<=10人。
    List<Performance> list = new ArrayList<>();
    String personnelCodes = condition.getPersonnelCode();
    if (!StringUtils.isBlank(personnelCodes)) {
      String[] personnelCodeArray = personnelCodes.split(",");
      condition.setSiteCode(SecurityContextUtil.getSiteCode());
      condition.setUserCode(SecurityContextUtil.getCurrentUser().getUserCode());
      for (int i = 0; i < (personnelCodeArray.length > 10 ? 10 : personnelCodeArray.length); i++) {
        condition.setPersonnelCode(personnelCodeArray[i]);
        Personnel personnel = personnelService.getPersonnelInfo(getSiteCode(), personnelCodeArray[i]);
        condition.setShiftingWorkCenterCode(personnel.getWorkCenterCode());
        List<Performance> dataList = personnelPerformanceService.statiscsPerformanceByCondition(condition);
        list.addAll(dataList);
      }
    }
    condition.setPersonnelCode(personnelCodes);
    condition.setData(list);
    model.addAttribute("page", condition);
    return "hr/performance/personnelPerf_statistics";
  }

  @RequestMapping("getPersonnelStatistics")
  @ResponseBody
  public DWZResult getPerformanceStatistics(PerformanceCondition condition) {

    try {
      int diff = DateUtils.getDateUtils(DateUtils.YYYY_MM_DD).getDaysOperationDate(condition.getMaxTheDate(), condition.getMinTheDate());
      //最长<=31天
      if (diff > 31) {
        return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "selectPerformanceOver.M"));
      }
    } catch (ParseException e) {
      log.error("{}", e);
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "parseFormat_error.M"));
    }
    //同时可以比较的人员数量限制<=10人。
    String personnelCodes = condition.getPersonnelCode();
    Map<String, Object> map = new HashMap<>();
    if (!StringUtils.isBlank(personnelCodes)) {
      String[] personnelCodeArray = personnelCodes.split(",");
      if (personnelCodeArray.length > 10) {
        return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "personnelOver10.M"));
      }
      condition.setSiteCode(SecurityContextUtil.getSiteCode());
      condition.setUserCode(SecurityContextUtil.getCurrentUser().getUserCode());

      List<String> dateList = null;
      try {
        dateList = DateUtils.getDateUtils()
            .getDatesBetweenTwoDate(condition.getMinTheDate(), condition.getMaxTheDate());
        map.put("dateList", dateList);
      } catch (ParseException e) {
        log.error("{}", e);
        return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
      }
      List<List<Double>> dList = new ArrayList<>();
      List<String> nameList = new ArrayList<>();
      for (int i = 0; i < personnelCodeArray.length; i++) {
        String personnelCode = personnelCodeArray[i];
        condition.setPersonnelCode(personnelCode);
        List<Double> dataList = new ArrayList<>();
        Personnel personnel = personnelService.getPersonnelInfo(getSiteCode(), personnelCode);
        nameList.add(personnel.getPersonnelName());
        for (String date : dateList) {
          PerformanceCondition pCondition = new PerformanceCondition();
          pCondition.setMaxTheDate(date);
          pCondition.setMinTheDate(date);
          pCondition.setPersonnelCode(condition.getPersonnelCode());
          pCondition.setMaterialCode(condition.getMaterialCode());
          pCondition.setShiftingWorkCenterCode(personnel.getWorkCenterCode());
          pCondition.setSiteCode(condition.getSiteCode());
          List<Performance> ps = personnelPerformanceService.statiscsPerformanceByCondition(pCondition);
          if (ps.size() == 0) {
            dataList.add(0.0);
          }

          if (ps.size() > 0) {
            Performance pp = ps.get(0);
            if (pp.getQuantity() == 0) {
              dataList.add(0.0);
            } else {
              dataList.add(new BigDecimal(pp.getWorkHours() / pp.getQuantity()).setScale(4, BigDecimal.ROUND_HALF_UP)
                  .doubleValue());
            }
          }
        }
        dList.add(dataList);
      }
      map.put("dataList", dList);
      map.put("nameList", nameList);
    }
    condition.setPersonnelCode(personnelCodes);
    return ajaxDone(map);
  }

}
